package sdk.org.apache.shiro.G2_使用.C05_认证_2认证匹配;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import com.titan.core.utils.debug.Timer;
import com.titan.core.utils.io.ConsoleUtils;

import sdk.org.apache.shiro.utils.ShiroUtils;


public class 使用HashedCredentialsMatcher认证匹配 {
    public static void main(String[] args) {
        Timer timer = Timer.$();
        try {
            run(timer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            timer.print("执行总用时");
            System.exit(0);
        }
    }
    
    private static void run(Timer timer) throws Exception {
        HashedCredentialsMatcher credentials = new HashedCredentialsMatcher();
        credentials.setHashAlgorithmName(ShiroUtils.HASH_ALGORITHM);
        credentials.setHashIterations(ShiroUtils.HASH_ITERATIONS);
        credentials.setStoredCredentialsHexEncoded(false);
        
        UserRealm realm = new UserRealm();
        realm.putAccount("admin", "1234");
        realm.setCredentialsMatcher(credentials);
        
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        securityManager.setRealm(realm);
        SecurityUtils.setSecurityManager(securityManager);
        
        // 登录验证
        for (int i = 1; i <= 9; i++) {
            loginTest("admin", "1234");
        }
        
        // 修改密码
        for (int i = 1; i <= 9; i++) {
            realm.putAccount("admin", "1234"+i);
            loginTest("admin", "1234"+i);
        }
    }
    
    
    private static void loginTest(String username, String password) throws Exception {
        try {
            Subject currentUser = ShiroUtils.login(username, password, true);
            try {
                ConsoleUtils.log("用户 ["+currentUser.getPrincipal()+"] 的登录状态："+currentUser.isAuthenticated());
            } finally {
                ShiroUtils.logout();
            }
        } catch (UnknownAccountException e) {
        } catch (IncorrectCredentialsException e) {
        }
    }
}
